/*
 * Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
 * 作者:马星俊
 */

import React, {useEffect, useState} from 'react';
import {TreeSelect} from "antd";
import service from '../service';
import {TreeSelectProps} from "antd/lib/tree-select";
import {eachTree} from "@/utils/utils";
import {TreeNodeModel} from "@/global";

export interface DeptTreeSelectProps extends TreeSelectProps<{}> {
  /** 主键 */
  deptId: string;
}

/**
 * 所属机构选择框
 */
const DeptTreeSelect = function (props: DeptTreeSelectProps) {
  const {deptId, ...rest} = props;
  const [parentList, setParentList] = useState<any[]>([]);
  const [defaultValue, setDefaultValue] = useState(['0']);
  /** 加载数据 */
  useEffect(() => {
    service.selectTreeList({}).then(r => {
      const tdata = r.data as TreeNodeModel[];
      eachTree(r.data, obj => {
        if (obj.id === deptId) {
          setDefaultValue([obj.parentId]);
        }
        ;
      })
      setParentList(tdata);
    });
  }, [deptId]);
  return (
    <TreeSelect
      {...rest}
      getPopupContainer={triggerNode => triggerNode.parentElement}
      treeIcon={true}
      allowClear={true}
      treeDefaultExpandedKeys={defaultValue}
      treeData={parentList}
    />
  );
};

export default DeptTreeSelect;
